package com.pinda.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.pinda.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author 黄杰
 * @since 2023-06-13
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("doLogin/{name}/{password}/{browser}/{operatingSystem}/{timestamp}")
    public SaResult doLogin(@PathVariable("name") String name,@PathVariable("password") String pwd,
                            @PathVariable("browser")  String browsers,
                            @PathVariable("operatingSystem") String operatingSystem,
                            @PathVariable("timestamp") String timeStamp) {
        return this.userService.doLogin(name, pwd,browsers,operatingSystem,timeStamp);
    }


    @Autowired
    private HttpSession session;
    /**
     * 刷新验证码
     * @param response
     * @throws IOException
     */
    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response) throws IOException {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha( 200, 100);
        String code = captcha.getCode();
        session.setAttribute("captcha", code);


        BufferedImage image = captcha.getImage();
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "png", os);
        os.flush();
        os.close();
    }


    /**
     * 验证验证码
     */
    @PostMapping("/verifyCaptcha")
    public String verifyCaptcha(@RequestBody Map<String, String> requestBody) {
        String captcha = requestBody.get("captcha");
        String storedCaptcha = (String) session.getAttribute("captcha");
        if (captcha.equalsIgnoreCase(storedCaptcha)) {
            // 验证成功
            return "success";
        } else {
            // 验证失败
            return "failure";
        }
    }
}
